package com.bjpowernode.money.timer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.money.constant.BidRankListConstant;
import com.bjpowernode.money.model.BidInfo;
import com.bjpowernode.money.model.RechargeRecord;
import com.bjpowernode.money.service.BidInfoService;
import com.bjpowernode.money.service.IncomeRecordService;
import com.bjpowernode.money.service.RechargeRecordService;
import com.bjpowernode.money.utils.HttpClientUtils;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Date;
import java.util.List;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/25
 */

@Component
public class SpringTask {

    @Reference(interfaceClass = IncomeRecordService.class,version = "1.0.0",timeout = 20000)
    private IncomeRecordService incomeRecordService;

    @Reference(interfaceClass = RechargeRecordService.class,version = "1.0.0",timeout = 20000)
    private RechargeRecordService rechargeRecordService;

    @Reference(interfaceClass = BidInfoService.class, version = "1.0.0", timeout = 20000)
    private BidInfoService bidInfoService;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;



    /**
     * 1、定时生成收益计划
     */
//    @Scheduled(cron = "0/5 * * * * ?")      // 测试每5s刷新
    public void generateIncomeRecord(){
        System.out.println("------generateIncomeRecordBegin-------");
        incomeRecordService.incomeRecordService();
        System.out.println("------generateIncomeRecordEnd-------");
    }

    /**
     * 2、定时刷新收益状态
     * 根据当前日期更新已经到期的收益状态
     */
//    @Scheduled(cron = "0/5 * * * * ?")      // 测试每5s刷新
//    @Scheduled(cron = "0 0 0 * * ? ")     // 表示每天0点刷新
    public void refreshIncomeStatus(){
        System.out.println("------refreshIncomeStatusBegin-------");
        Date currentTime = new Date();
        // 查出收益日期，与当前时间比较
        incomeRecordService.updateStatusAndFinanceByDate(currentTime);
        System.out.println("------refreshIncomeStatusEnd-------");
    }

    /**
     * 3、定时刷新充值状态
     */
    @Scheduled(cron = "0/5 * * * * ?")
//    @Scheduled(cron = "0 0 0 * * ? ")     // 表示每天0点刷新
    public void refreshForRecharge(){
        System.out.println("------refreshForRechargeBegin-------");

        // 1、查询状态为0的订单
        List<RechargeRecord> rechargeRecordList = rechargeRecordService.queryByStatus();

        // 遍历查询pay模块 根据状态操作
        for (RechargeRecord rechargeRecord : rechargeRecordList) {
            try {
                String rechargeNo = rechargeRecord.getRechargeNo();
                String result = HttpClientUtils.doGet("http://localhost:8007/007-money-pay/loan/pay/queryOrder?out_trade_no=" + rechargeNo);
//                String result = HttpClientUtils.doGet("http://192.168.230.128:8007/007-money-pay/loan/pay/queryOrder?out_trade_no=" + rechargeNo);
                // 解析异步查询到的支付状态数据
                JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("alipay_trade_query_response");
                String code = jsonObject.getString("code");
                String trade_status = jsonObject.getString("trade_status");
                if (StringUtils.equals("10000", code)) {

                    if (StringUtils.equals("WAIT_BUYER_PAY", trade_status)) {
                        // 短信通知支付
                        /*map.put("appkey", "61571f734d70669ee92aa8d1cd683671-bak");
                        map.put("mobile", user_session.getPhone());
                        map.put("content", "感谢投资，请尽快支付");
                        HttpClientUtils.doGet("https://way.jd.com/chuangxin/dxjk", map);        // 只通知不关系结果*/
                    }
                    if (StringUtils.equals("TRADE_CLOSED", trade_status)) {
                        // 未付款交易超时关闭，或支付完成后全额退款  支付状态改为2
                        rechargeRecordService.rechargeFail(rechargeNo);
                    }
                    if (StringUtils.equals("TRADE_SUCCESS", trade_status)) {
                        // 交易成功
                        Integer userId = rechargeRecord.getUid();
                        Double rechargeMoney = rechargeRecord.getRechargeMoney();
                        int num = rechargeRecordService.rechargeSuccess(rechargeNo,rechargeMoney,userId);
                        if (num != 0) {
                            // 短信通知 到账
                            /*map.put("appkey", "61571f734d70669ee92aa8d1cd683671-bak");
                            map.put("mobile", user_session.getPhone());
                            map.put("content", "已到账");
                            HttpClientUtils.doGet("https://way.jd.com/chuangxin/dxjk", map);        // 只通知不关系结果*/
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("------refreshForRechargeEnd---------");
    }

    /**
     * 4、定时刷新排行榜
     */
    @Scheduled(cron = "0/10 * * * * ?")
//    @Scheduled(cron = "0 0 0 * * ? ")     // 表示每天0点刷新
    public void refreshRankList(){
        System.out.println("------refreshRankListBegin-------");
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 查出所有投资记录
        List<BidInfo> bidInfoList = bidInfoService.queryAllBidInfo();
        // 遍历后返给redis
        for (BidInfo bidInfo : bidInfoList) {
            // zSet将id按照投资金额排名存入redis
            redisTemplate.opsForZSet().add(BidRankListConstant.BID_RANK_LIST, bidInfo.getId(), bidInfo.getBidMoney());
            redisTemplate.expire(BidRankListConstant.BID_RANK_LIST, Duration.ofDays(1));
        }

        System.out.println("------refreshRankListEnd-------");

    }

}
